#include "yb_form_xmdz.h"
#include "ui_yb_form_xmdz.h"
#include "pub_var.h"
#include <QSqlRecord>
#include <QMessageBox>
#include <QSqlError>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>

Form_xmdz::Form_xmdz(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_xmdz)
{
    ui->setupUi(this);

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/xmdz").toRect();
    this->setGeometry(rct);

    ui->rb_1312->setVisible(false);//基本无用

    //数据库连接
    qro = new QSqlQuery(pub::db_o);
    qrm = new QSqlQuery(pub::db_m);

    qrm->exec("select dic_value, dic_label from com_dict_new "
              " where dic_type = 'LIST_TYPE' order by dic_value");
    ui->cbbList->clear();
    QString itm;
    while(qrm->next()){
        itm = qrm->value(0).toString().trimmed() ;
        itm.append(" ");
        itm.append(qrm->value(1).toString().trimmed());
        ui->cbbList->addItem(itm);
    }

    tm = new QTimer(this);

    connect(tm, SIGNAL(timeout()), this, SLOT(onTimeOut()));

    //网络参数
    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    ui->cbbList->setCurrentIndex(-1);

    sq = "select dept_name, dept_code from com_department "
         "where valid_state = '1' order by dept_name";
    qDebug()<<"提取门诊科室："<<sq;
    oper_dept = pub::fillCombo(ui->cbb_dept_code_2, sq, -1, qro);
    ui->cbb_dept_code_2->addItem("全部");
    oper_dept.append("^全部^");

    num_pack_qty_center = 0;
    num_pack_qty_local = 0;


}

Form_xmdz::~Form_xmdz()
{
    delete ui;
}

void Form_xmdz::on_pbExit_clicked()
{
    this->close();
}

void Form_xmdz::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/xmdz", QVariant(this->geometry()));
    destroyW("xmdz");

}

void Form_xmdz::on_rbLocal_clicked()
{
    display(ui->leSearch->text());
}

void Form_xmdz::on_rb_1312_clicked()
{
    selfPay = false;
    display(ui->leSearch->text());

}

void Form_xmdz::on_rbCenter_clicked()
{
    selfPay = false;
    display(ui->leSearch->text());
}

void Form_xmdz::on_rbCompared_clicked()
{
    display(ui->leSearch->text());
}

void Form_xmdz::on_rbSelfPay_clicked()
{
    selfPay = true;
    display(ui->leSearch->text());
}

void Form_xmdz::on_cbbList_curIndChanged(int)
{
    display(ui->leSearch->text());
}

void Form_xmdz::onTimeOut()
{
    tm->stop();
    display(ui->leSearch->text());
}

void Form_xmdz::on_leSearch_textChanged(QString s)
{
    Q_UNUSED(s)
    //tm->stop();
    //tm->start(500);
}

void Form_xmdz::display_local_drug(QString key, QString fee_type, QString self_made)
{

    sq = " select pha.drug_code 药品ID, pha.trade_name 药品名称, pha.approve_info 批准文号,"  //0-2
         " pha.fee_code 费用类别, pha.specs 规格, pha.retail_price 价格,"//3-5
         " pha.pack_unit 包装单位, pha.pack_qty 包装数量 ,pha.producer_code, comp.HIS_CODE " //6-9
         " from pha_com_baseinfo pha"
         " left join fin_com_compare comp "
         " on comp.fixmedins_hilist_id = pha.drug_code "
         " where pha.fee_code in (%2) "
         " and (pha.spell_code like upper('%%1%') or pha.trade_name like '%%1%') "
         " and pha.valid_state = '1' and pha.self_flag = %3 "
         " and comp.HIS_CODE is null "
         " order by pha.trade_name";
    sq = sq.arg(key).arg(fee_type).arg(self_made);
    qDebug()<<"药品本地目录  : "<<sq;

    mdList.setQuery(sq, pub::db_o);
    double width = ui->tvDisplay->width() - 50;
    ui->tvDisplay->setModel(&mdList);
    pub::setColumnWidth(ui->tvDisplay, "0.2^0.2^0.2^0.1^0.1^0^0.1^0.1^0^0", width);

}

void Form_xmdz::display_local_undrug(QString key, QString fee_type)
{
    QString dept = "";
    if(!ui->cbb_dept_code_2->currentText().isEmpty())
    {
        int pos = pub::searchStr(oper_dept, "^", ui->cbb_dept_code_2->currentText());

        dept = " and un.exedept_code like '" + pub::getStr(oper_dept, "^", pos + 1) + "%'";
    }

    sq = " select un.item_code 项目ID, un.item_name 项目名称, un.oper_date 开始时间, "
         " un.fee_code 费用类别, un.stock_unit 单位 , un.unit_price 价格, "
         " un.spell_code, un.valid_state , comp.HIS_CODE  "
         " from fin_com_undruginfo un "
         " left join fin_com_compare comp on comp.fixmedins_hilist_id = un.item_code "
         " where (un.spell_code like upper('%%1%') or un.item_name like upper('%%1%'))"
         " and un.valid_state = '1'"
         " and un.fee_code in(%2) "
         " and comp.HIS_CODE is null %3"
         " and un.unitflag = '0'"
         " order by un.item_name ";

    sq = sq.arg(key).arg(fee_type).arg(dept);
    qDebug()<<"非药品本地目录  : "<<sq;
    mdList.setQuery(sq, pub::db_o);
    double width = ui->tvDisplay->width() - 50;
    ui->tvDisplay->setModel(&mdList);
    pub::setColumnWidth(ui->tvDisplay, "0.2^0.2^0.2^0.1^0.1^0.1",width);

}

void Form_xmdz::display(QString key)
{

    if(ui->cbbList->currentText().isEmpty())
    {
        QMessageBox::information(this, "注意", "未选择对照类别！");
        return; //
    }

    list_type = pub::getStr(ui->cbbList->currentText()," ",1); //目录类别

    mdList.setQuery(NULL);  //清空当前显示
    qApp->processEvents();

    if(ui->rbLocal->isChecked()){   //当前显示本地目录

        if(list_type == "102")
        {
            //中草药
            display_local_drug(key, "'003'", "0");
        }
        else if(list_type == "201")
        {
            //诊疗项目
            display_local_undrug(key, "'004','005','006','007','008','009',"//'003',
                                      "'011','012','013','014','015','016','017',"
                                      "'018','021','022','023','024'");
        }
        else if(list_type == "101")
        {
            //西药,中成药
            display_local_drug(key, "'001','002'", "'0'");

        }
        else if(list_type == "103")
        {
            //院内制剂
            display_local_drug(key, "'001','002'", "'1'");
        }
        else if(list_type == "301")
        {
            //耗材
            display_local_undrug(key, "'010'");
        }

    }
    else if(ui->rbCenter->isChecked())
    {
        //当前显示中心目录
        if(list_type == "101"){  //中西药

            sq = "select 药品ID, 注册名称 , 批准文号 , 生产企业名称, 药品规格, 单位,包装数量"
                 " from (select 医疗目录编码 药品ID, 注册名称 , 批准文号 , 生产企业名称, "
                 " concat(concat(药品规格,'/'),包装材质) 药品规格, 最小包装数量 包装数量,"
                 " 最小包装单位 单位 "
                 " from new_down_1301 "
                 " where %1 "
                 " limit 1000 ) base "
                 " join new_down_1312 s on s.hilist_code = 药品ID " //
                    " and list_type = '101' and begndate < CURDATE() "
                    " and (enddate is null or enddate > CURDATE()) "
                    " order by 生产企业名称, 药品规格";  //

            if(ui->rb_fuzzy->isChecked())
            {
                sq = sq.arg("批准文号 like '%" + key + "%' or 注册名称 like '%" + key + "%'");
            }
            else
            {
                sq = sq.arg("批准文号 = '" + key + "' or 注册名称 = '" + key + "'");
            }

            mdList.setQuery(sq, pub::db_m);
            qDebug()<<"中心目录，中西药 "<<sq;
            double width = ui->tvDisplay->width() - 50;
            ui->tvDisplay->setModel(&mdList);
            pub::setColumnWidth(ui->tvDisplay, "0.15^0.2^0.15^0.1^0.2^0.1^0.1",width);

        }else if(list_type == "201"){  //诊疗项目

            sq = " select 项目ID, 项目名称, 项目内容,说明 from "
                 "(select 医疗目录编码 项目ID, 医疗服务项目名称 项目名称, 诊疗项目内涵 项目内容,诊疗项目说明 说明"
                 " from new_down_1305 where %1 limit 1000 "
                 " union "
                 " select 医疗目录编码 项目ID, 医疗服务项目名称 项目名称, 医疗服务项目输出 项目内容,诊疗项目说明 说明"
                 " from new_down_1321 where %1 limit 1000"
                 ") base "
                 " join new_down_1312 s on s.hilist_code = base.项目ID "  //
                    " and list_type = '201' and begndate < CURDATE() "
                    " and (enddate is null or enddate > CURDATE())"
                    " order by 项目名称";

            if(ui->rb_fuzzy->isChecked())
            {
                sq = sq.arg("医疗服务项目名称 like '%" + key + "%'");
            }
            else
            {
                sq = sq.arg("医疗服务项目名称 = '" + key + "'");
            }

            qDebug()<<"中心目录，诊疗项目 "<<sq;
            mdList.setQuery(sq, pub::db_m);
            double width = ui->tvDisplay->width() - 50;
            ui->tvDisplay->setModel(&mdList);
            pub::setColumnWidth(ui->tvDisplay, "0.3^0.3^0.2^0.2",width);

        }
        else if(list_type == "103")
        {
            //院内制剂
            sq = " select 药品ID,药品商品名,批准文号,剂型,药品规格,国家医保药品目录编号,包装数量 from "
                 "( select 医疗目录编码 药品ID,药品商品名,批准文号,剂型,药品规格,国家医保药品目录编号,最小包装数量 包装数量"
                 " from new_down_1303 "
                 " where %1 ) base " // limit 1000
                 " join new_down_1312 s on s.hilist_code = 药品ID "  //
                    " and list_type = '103' and begndate < CURDATE() "
                    " and (enddate is null or enddate > CURDATE()) "
                    " order by 药品商品名";

            if(ui->rb_fuzzy->isChecked())
            {
                sq = sq.arg("药品商品名 like '%" + key + "%'");
            }
            else
            {
                sq = sq.arg("药品商品名 = '" + key + "'");
            }

            mdList.setQuery(sq, pub::db_m);
            qDebug()<<"中心目录，院内制剂 "<<sq;
            double width = ui->tvDisplay->width() - 50;
            ui->tvDisplay->setModel(&mdList);
            pub::setColumnWidth(ui->tvDisplay, "0.2^0.2^0.2^0.2^0.2",width);
        }
        else if(list_type == "301")
        {
            //耗材
            sq = "select 项目ID,耗材名称,规格,产品型号,注册备案号,生产企业名称 from "
                 "(select 医疗目录编码 项目ID,耗材名称,规格,产品型号,注册备案号,生产企业名称"
                 " from new_down_1306 where  %1  limit 1000) base "
                 " join new_down_1312 s on s.hilist_code = 项目ID "  //
                    " and list_type = '301' and begndate < CURDATE() "
                    " and (enddate is null or enddate > CURDATE()) ";

            if(ui->rb_fuzzy->isChecked())
            {
                sq = sq.arg("耗材名称 like '%" + key + "%' or 注册备案号 like '%" + key + "%'");
            }
            else
            {
                sq = sq.arg("耗材名称 = '" + key + "' or 注册备案号 = '" + key + "'");
            }


            mdList.setQuery(sq, pub::db_m);
            qDebug()<<"中心目录，耗材 "<<sq;
            double width = ui->tvDisplay->width() - 50;
            ui->tvDisplay->setModel(&mdList);
            pub::setColumnWidth(ui->tvDisplay, "0.2^0.15^0.15^0.15^0.15^0.15^0^0^0^0^0",width);

        }else if(list_type == "102"){  //中草药
            sq = " select 药品ID, 单味药名称 , 药材名称, 药材种来源 from "
                 " (select 医疗目录编码 药品ID, 单味药名称 , 药材名称, 药材种来源 "
                 " from new_down_1302 "
                 " where %1 limit 1000) base "
                 " join new_down_1312 s on s.hilist_code = 药品ID "  //
                    " and list_type = '102' and begndate < CURDATE() "
                    " and (enddate is null or enddate > CURDATE()) "
                    " order by 单味药名称";;

            if(ui->rb_fuzzy->isChecked())
            {
                sq = sq.arg("单味药名称 like '%" + key + "%'");
            }
            else
            {
                sq = sq.arg("单味药名称 = '" + key + "'");
            }

            mdList.setQuery(sq, pub::db_m);
            qDebug()<<"中心目录，中草药 ："<<sq;
            double width = ui->tvDisplay->width() - 50;
            ui->tvDisplay->setModel(&mdList);
            pub::setColumnWidth(ui->tvDisplay, "0.2^0.2^0.2^0.2",width);
        }

    }
    else if(ui->rb_1312->isChecked())
    {
        qDebug()<<"中心 1312 目录 ";
        //当前显示中心目录
        sq = " select hilist_code, hilist_name,memo,begndate,enddate "
             " from new_down_1312"
             " where list_type = '%1' and %2 "
             " and (enddate is null or enddate > CURDATE()) "
             " order by hilist_name";

        sq = sq.arg(list_type);

        if(ui->rb_fuzzy->isChecked())
        {
            sq = sq.arg("hilist_name like '%" + key + "%'");
        }
        else
        {
            sq = sq.arg("hilist_name = '" + key + "'");
        }

        qDebug()<<sq<<"\n";
        mdList.setQuery(sq, pub::db_m);
        mdList.setHeaderData(0, Qt::Horizontal, "项目ID");
        mdList.setHeaderData(1, Qt::Horizontal, "项目名称");
        mdList.setHeaderData(2, Qt::Horizontal, "项目内容");
        mdList.setHeaderData(3, Qt::Horizontal, "起始日期");
        mdList.setHeaderData(4, Qt::Horizontal, "终止日期");


        double width = ui->tvDisplay->width() - 50;
        ui->tvDisplay->setModel(&mdList);
        ui->tvDisplay->setColumnWidth(0, width * 0.35);
        ui->tvDisplay->setColumnWidth(1, width * 0.2);
        ui->tvDisplay->setColumnWidth(2, width * 0.2);
        ui->tvDisplay->setColumnWidth(3, width * 0.1);
        ui->tvDisplay->setColumnWidth(4, width * 0.1);
    }
    else if(ui->rbSelfPay->isChecked())
    {
        //当前显示中心自费目录

        sq = " select ownpay_code 编码, ownpay_name 项目名称, memo 备注 ,chrgitm_attr 项目类别 from  new_down_1363 ";
        mdList.setQuery(sq, pub::db_m);
qDebug()<<"中心自费目录，不细分 "<<sq;
        double width = ui->tvDisplay->width() - 50;
        ui->tvDisplay->setModel(&mdList);
        pub::setColumnWidth(ui->tvDisplay, "0.2^0.2^0.2^0.2", width, 10);

    }
    else if(ui->rbCompared->isChecked())
    {
        //当前显示已对照目录
        //fixmedins_hilist_name
        sq = "select comp.fixmedins_hilist_id 本地代码, comp.his_name 本地名称,"
             " comp.med_list_codg 中心代码, comp.center_name 中心名称, "
             " center_specs 规格, center_producer 生产商"
             " from fin_com_compare comp"
             " %1 "
             " where comp.new_flag = '1' and comp.list_type = '%2' "
             " and (his_spell like '%%3%' or %4) "
             " order by comp.his_name ";

        QString dept = "";
        if(list_type == "201" || list_type == "301"
                || list_type == "401" || list_type == "501"  )
        {
            //非药品
            if(!ui->cbb_dept_code_2->currentText().isEmpty())
            {
                int pos = pub::searchStr(oper_dept, "^", ui->cbb_dept_code_2->currentText());
                dept = pub::getStr(oper_dept, "^", pos + 1);//
                dept = " join fin_com_undruginfo un "
                       " on un.item_code = comp.fixmedins_hilist_id "
                       " and un.exedept_code like '" + dept + "%'";
            }
        }

        sq = sq.arg(dept).arg(list_type).arg(key.toUpper());

        if(ui->rb_fuzzy->isChecked())
        {
            sq = sq.arg("his_name like '%" + key + "%'");
        }
        else
        {
            sq = sq.arg("his_name = '" + key + "'");
        }


qDebug()<<"当前显示已对照目录"<<sq;
        mdList.setQuery(sq, pub::db_o);
        double width = ui->tvDisplay->width() - 50;
        ui->tvDisplay->setModel(&mdList);
        pub::setColumnWidth(ui->tvDisplay, "0.1^0.15^0.15^0.15^0.2^0.15",width, 10);
    }


}

void Form_xmdz::on_pbCompare_clicked()
{

    if(centerID.isEmpty() || localID.isEmpty()
            || ui->leCenterDescription->text().isEmpty()
            || ui->leLocalDescription->text().isEmpty())
    {
        QMessageBox::information(this,"注意","请先选定本地目录和中心目录之后再做对照操作！");
        return;
    }

    if( (list_type == "101" || list_type == "103" ) && !selfPay)
    {
        //西药中成药、自制剂，且非自费目录，检查本地包装数量与中心包装数量是否一致
        if(num_pack_qty_local != num_pack_qty_center)
        {
            QString pack_local = QString::number(num_pack_qty_local);
            QString pack_center = QString::number(num_pack_qty_center);

            QMessageBox::information(this,"注意","选定药品的本地包装数量 "
                                     + pack_local +" 与中心包装数量 "
                                     + pack_center +" 不一致！");
            return;
        }
    }

    QJsonObject in; //入参
    QJsonArray jsar;

    QJsonObject jo_base;

    if(selfPay){  //自费项目

        jo_base.insert("fixmedins_hilist_id", localID);//定点医药机构目录编号	字符型	30		Y
        jo_base.insert("fixmedins_hilist_name", item_name);//	定点医药机构目录名称	字符型	200		Y
        jo_base.insert("list_type", list_type);//	目录类别	字符型	30	Y	Y
        jo_base.insert("med_list_codg", centerID);//	医疗自费目录编码	字符型	30		Y
        jo_base.insert("begndate","2024-01-01");//	开始日期	日期型			Y
        jo_base.insert("enddate","2099-12-31");//enddate	结束日期	日期型			Y
        jo_base.insert("spec", localSpecs);//spec	规格	字符型	200		Y
        jo_base.insert("prodname", item_name);//prodname	商品名称	字符型	100		Y
        qro->exec("select fac_name from pha_com_company where fac_code = '"+producer_code+"'");
        qro->next();
        QString pdn = qro->value(0).toString();
        if(pdn.isEmpty())
        {
            pdn = "-";
        }
        jo_base.insert("prodentp_name", pdn);//prodentp_name	生产企业	字符型	100		Y
        jo_base.insert("pric", localPrice.toDouble());//pric	单价	数值型	10		Y

        jsar << jo_base;

        in.insert("data",jsar);

        QString info;
        QJsonObject jsonRet;

        if( ! pub::call_business( "3361", in, info, jsonRet, "", true , manager, request))
        {
            QMessageBox::warning(this, "注意", info);
            return;
        }

    }
    else //医保项目
    {
        //查询是否存在重复对照信息
        sq = " select * from fin_com_compare where med_list_codg = '" + centerID + "'";
        qDebug()<<"查询是否存在重复对照信息 : "<<sq;
        qro->exec(sq);
        if(qro->next())
        {
            QMessageBox::warning(this, "注意", "指定的中心编码已经存在，请注意核实！");
            //return;
        }

        jo_base.insert("fixmedins_hilist_id", localID);//	定点医药机构目录编号
        jo_base.insert("fixmedins_hilist_name", item_name);//	定点医药机构目录名称
        jo_base.insert("list_type", list_type);	//目录类别
        jo_base.insert("med_list_codg", centerID);	//医疗目录编码
        jo_base.insert("begndate", QDate::currentDate().toString("yyyy-MM-dd")+" 00:00:00");	//开始日期
        jo_base.insert("enddate", "2099-12-31 23:59:59");	//结束日期

        jsar << jo_base;

        in.insert("data",jsar);

        QString info;
        QJsonObject jsonRet;

        if( ! pub::call_business( "3301", in, info, jsonRet, "", true , manager, request))
        {
            QMessageBox::warning(this, "注意", info);
            return;
        }
    }

    if(selfPay)
    {
        QMessageBox::information(this,"note","自费项目对照成功！");
    }else{
        QMessageBox::information(this,"note","医保项目对照成功！");
    }


    //清除可能存在的旧对照信息
    qro->exec("delete from fin_com_compare where fixmedins_hilist_id = '"+localID+"'");

    //保存新对照信息
    QString compare_flag;
    if(selfPay)
    {
        compare_flag = "1";
    }else{
        compare_flag = "0";
    }

    sq = "insert into fin_com_compare "
         "(oper_date,new_flag,pact_code,his_code,center_code,list_type,"
         " fixmedins_hilist_id, his_name, med_list_codg,"
         " fixmedins_hilist_name, begndate,"
         " med_chrgitm_type, center_item_grade,center_name,"
         "his_spell,compare_flag,his_specs,center_specs,center_producer) "
         " values (sysdate,'1','2',lower('"
            +localID+"'),'"
            +centerID+"','"
            + list_type
            +"','" + localID
            +"','" + item_name
            +"','" + centerID
            +"','" + hilist_name
            +"',sysdate, '"
            + med_chrgitm_type
            +"','"+ chrgitm_lv
            +"','"+ hilist_name
            +"','"+ pinyin
            +"','"+ compare_flag
            +"','"+ localSpecs
            +"','"+ center_specs
            +"','"+ center_producer.left(100)  //某些治疗项目说明超宽
            +"')" ;
qDebug()<<"保存已经对照的信息："<<sq;
    if(!qro->exec(sq)){
        QMessageBox::information(this,"note","项目对照本地存储失败！"+qro->lastError().text());
        qDebug()<<qro->lastError().text();
        qDebug()<<qro->lastQuery();
    }

    //查找新医保编码对应的 icpc 编码
    QStringList lst = centerID.split("-");

    sq = " select icpc_code from new_down_1362 "
         " where chrgitm_nat_code = '" + lst[0] + "'";

    qrm->exec(sq);
    QString icpc_code;
    if(qrm->next())
    {
        icpc_code = qrm->value(0).toString();
    }
    else
    {
        icpc_code = "0";
    }

    //变更 icpc 对应关系
    sq = " update com_dict_icpc set nat_code = '%1', icpc_code = '%2' "
         " where item_code = '%3'";
    sq = sq.arg(centerID)
            .arg(icpc_code)
            .arg(localID);

    qDebug()<<"变更 icpc 对应关系 : "<<sq;

    qrm->exec(sq);

    //对照成功之后，医保中心编码可能发生变化，进销存模块需要重新上传此品种信息

    sq = " update pha_com_stockinfo set upload_no = 0 "
         " where drug_code = '" + localID + "'";

    if(!qro->exec(sq))
    {
        QMessageBox::information(this,"note","重置进销存上传标志失败！");
        qDebug()<<"重置进销存上传标志：";
        qDebug()<<qro->lastQuery();
        qDebug()<<qro->lastError().text();

    }

    localID = "";
    centerID = "";

    ui->leLocalDescription->clear();
    ui->leCenterDescription->clear();

    num_pack_qty_center = 0;
    num_pack_qty_local = 0;

}

void Form_xmdz::on_pbUncompare_clicked()
{
    if(centerID.isEmpty() || localID.isEmpty()
            || ui->leCenterDescription->text().isEmpty() || ui->leLocalDescription->text().isEmpty()){
        QMessageBox::information(this,"注意","请先选定本地目录和中心目录之后再操作！");
        return;
    }

    //检查指定项目为医保对照还是自费对照
    qro->exec("select compare_flag from fin_com_compare where fixmedins_hilist_id = '"+localID+"'");
    QString compare_flag = "";
    if(qro->next())
    {
        compare_flag = qro->value(0).toString();
    }

    if(compare_flag == "1") //项目为自费对照
    {
        //自费项目，直接删除
        qro->exec("delete from fin_com_compare where fixmedins_hilist_id = '"+localID+"'");
        QMessageBox::information(this,"note","自费项目，本地目录已删除！");
        localID = "";
        centerID = "";

        ui->leLocalDescription->clear();
        ui->leCenterDescription->clear();
        return;
    }

    //医保项目，进行取消对照操作
    QJsonObject in; //入参
    QJsonObject inpu,inpud; // 入参 input 段

    putBaseIn(in, "3302");

    inpu.insert("fixmedins_code", pub::hos_ybbh);	//医疗目录编码 -00110200001000003
    inpu.insert("fixmedins_hilist_id", localID);//	定点医药机构目录编号
    inpu.insert("list_type", list_type);	//目录类别
    inpu.insert("med_list_codg", centerID);	//医疗目录编码 -00110200001000003
    //inpu.insert("fixmedins_hilist_name", item_name);	//

    inpud.insert("data", inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);
    qDebug()<<" 3302 indoc"<<indoc;
    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = naaManager0.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意", "3302 http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意", "3302 : " + reply->errorString());
        return ;
    }


    QByteArray btret = reply->readAll();
    QString t = QString::fromLocal8Bit(btret);

    QJsonParseError json_error;

    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意", currentInfno + " 返回信息解析错误 " + json_error.errorString());

        return ;
    }
    qDebug()<< currentInfno + " outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    //保存出出参日志

    sq = "update com_business set tmstmp = now(), v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +  "  where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }


    if(jsob.value("infcode").toInt() != 0)
    {
        QString t = jsob.value("err_msg").toString();
        t = currentInfno + " 交易失败：" + t ;
        qDebug()<<t;
        QMessageBox::information(this, "注意", t);
        return;
    }
    qro->exec("delete from fin_com_compare where fixmedins_hilist_id = '"+localID+"'");
    sq = "delete from new_down_1317 where medins_list_codg ='" + localID+"'";
    qDebug()<<sq;
    qrm->exec(sq);

    QMessageBox::information(this,"note","项目对照撤销完成！");
    localID = "";
    centerID = "";

    ui->leLocalDescription->clear();
    ui->leCenterDescription->clear();

}

void Form_xmdz::on_pbTest_clicked()
{
    display(ui->leSearch->text().trimmed());
}

void Form_xmdz::putBaseIn( QJsonObject &in, QString code)
{
    QString inp;
    inp = pub::getYbStrJ(code,"");   //
    if(inp.isEmpty()){
        pub::useInsurance = false;  //设置医保不可用
        QMessageBox::information(this,"note","申请交易流水号失败！");
        return; //未能成功申请交易流水号
    }
    currentMsgid = inp;
    currentInfno = code;
    in.insert("infno", code);
    in.insert( "msgid", inp);
    in.insert("mdtrtarea_admvs", pub::hos_insuplc);

    in.insert("insuplc_admdvs","210100");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);

}

void Form_xmdz::on_tvDisplay_doubleClicked(const QModelIndex &index)
{


    if(ui->rbLocal->isChecked())
    {
        localID = index.siblingAtColumn(0).data(0).toString();
        item_name = index.siblingAtColumn(1).data(0).toString();
        ui->leLocalDescription->setText(localID + "/"
                                        + item_name+ "/"
                                        + index.siblingAtColumn(2).data(0).toString());
        if(list_type == "103" || list_type == "101")
        {
            localSpecs = index.siblingAtColumn(4).data(0).toString();
            localPrice = index.siblingAtColumn(5).data(0).toString();
            producer_code = index.siblingAtColumn(8).data(0).toString();
            num_pack_qty_local = index.siblingAtColumn(7).data(0).toInt();

        }else{
            producer_code = "-";
            localSpecs = "-";
            localPrice = index.siblingAtColumn(5).data(0).toString();
        }
        //ui->lePinyin->setText(index.siblingAtColumn(2).data(0).toString());
    }
    else if(ui->rbCenter->isChecked())
    {


            //医疗目录编码, 注册名称, 批准文号, 生产企业名称, 药品规格, 最小包装数量, 最小包装单位
            centerID = index.siblingAtColumn(0).data(0).toString();
            hilist_name = index.siblingAtColumn(1).data(0).toString();

            center_specs = index.siblingAtColumn(4).data(0).toString();
            center_producer = index.siblingAtColumn(3).data(0).toString();
            ui->leCenterDescription->setText(centerID+ "/" + hilist_name);

            num_pack_qty_center = index.siblingAtColumn(6).data(0).toInt();


            sq = " select chrgitm_lv from new_down_1312 "
                 " where list_type = '"
                    +list_type + "' and hilist_code = '" + centerID + "' ";
            qrm->exec(sq);
            if(qrm->next())
            {
                chrgitm_lv = qrm->value(0).toString();
            }
            else
            {
                chrgitm_lv = "";
            }
            qDebug()<<"根据医保目录编码提取项目等级";
            qDebug()<<sq;
            qDebug()<<"项目等级 : "<<chrgitm_lv<<"\n";

    }
    else if(ui->rb_1312->isChecked())
    {
        //项目ID , 项目名称 , 项目内容 , 起始日期　, 终止日期
            centerID = index.siblingAtColumn(0).data(0).toString();
            hilist_name = index.siblingAtColumn(1).data(0).toString();

            ui->leCenterDescription->setText(centerID+ "/" + hilist_name);

            //center_specs = index.siblingAtColumn(4).data(0).toString();
            //center_producer = index.siblingAtColumn(3).data(0).toString();


            //num_pack_qty_center = index.siblingAtColumn(6).data(0).toInt();


    } else if(ui->rbSelfPay->isChecked()){

            centerID = index.siblingAtColumn(0).data(0).toString();
            hilist_name = index.siblingAtColumn(1).data(0).toString();
            ui->leCenterDescription->setText(centerID + "/" + hilist_name);

    }else{
        //已对照项目
        localID = index.siblingAtColumn(0).data(0).toString();
        centerID = index.siblingAtColumn(2).data(0).toString();
        ui->leLocalDescription->setText(localID + "/" + index.siblingAtColumn(1).data(0).toString());

        QString t = index.siblingAtColumn(3).data(0).toString();
        ui->leCenterDescription->setText(centerID + "/" + t );
    }

}

void Form_xmdz::postRequestFinished(QNetworkReply *)
{
    qDebug()<<"http return ! ";

    httpFinished = true;
    QVariant statusCode = rpl->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意", " 3301/3302 http 请求状态错误: " + statusCode.toString());
        httpSuccess = false;
        return;
    }

    QNetworkReply::NetworkError err = rpl->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意", "3301/3302 " + rpl->errorString());
        httpSuccess = false;
        return;
    }else{

        httpSuccess = true;

    }
}

void Form_xmdz::on_leSearch_returnPressed()
{
    display( ui->leSearch->text().trimmed());
}


void Form_xmdz::on_pushButton_clicked()
{

    if(centerID.isEmpty() || localID.isEmpty()
            || ui->leCenterDescription->text().isEmpty() || ui->leLocalDescription->text().isEmpty()){
        QMessageBox::information(this,"注意","请先选定本地目录和中心目录之后再操作！");
        return;
    }

    qro->exec("delete from fin_com_compare where fixmedins_hilist_id = '"+localID+"'");
    sq = "delete from new_down_1317 where medins_list_codg ='" + localID+"'";
    qDebug()<<sq;
    qrm->exec(sq);

    QMessageBox::information(this,"note","本地对照数据删除完成！");
    localID = "";
    centerID = "";

    ui->leLocalDescription->clear();
    ui->leCenterDescription->clear();
}


